import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, Select, Button, Table, DatePicker, Input } from 'antd';
import moment from 'moment';
import styles from './MainProductsList.less';

const Option = Select.Option;

@connect(({ MainProduct }) => ({
  productList: MainProduct.productList,
  updateDidFinish: MainProduct.updateDidFinish,
}))
class MainProductsList extends Component {
  state = {
    page_num: 1,
    modalVisibility: false,
    selectedRows: [],
    modalId: undefined,
    modalProductName: '',
    modalProductType: 0,
    modalOperation: 'new',
  };

  updateData() {
    const { dispatch } = this.props;
    dispatch({
      type: 'MainProduct/queryMainProductList',
      payload: {
        page_num: this.state.page_num,
        page_size: 10,
      },
    });
  }

  componentDidMount() {
    this.setState({ loading: false });
    this.updateData();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.updateDidFinish !== this.props.updateDidFinish) {
      this.updateData();
    } else if (prevProps.productList !== this.props.productList) {
      this.setState({ selectedRows: [] });
    }
  }

  render() {
    let { productList } = this.props;

    const cols = [
      {
        title: '产品名称',
        dataIndex: 'product_name',
        key: 'product_name',
      },
      {
        title: '业务分类',
        dataIndex: 'product_type_name',
        key: 'product_type_name',
      },
      {
        title: '操作',
        key: 'operations',
        dataIndex: 'id',
        render: (text, row, index) => (
          <a
            onClick={() => {
              handleEditClick(index);
            }}
          >
            编辑
          </a>
        ),
      },
    ];

    let pager = {
      defaultCurrent: 1,
      total: productList.total_count,
      onChange: (page, pageSize) => {
        this.setState({ page_num: page }, () => {
          this.updateData();
          this.setState({ selectedRows: [] });
        });
      },
    };

    let handleEditClick = index => {
      this.setState({
        modalId: productList.data_list[index].id,
        modalProductName: productList.data_list[index].product_name,
        modalProductType: productList.data_list[index].product_type_id,
        modalVisibility: true,
        modalOperation: 'update',
      });
    };

    let handleDeleteClick = () => {
      if (this.state.selectedRows.length > 0) {
        const { dispatch } = this.props;
        let res = [];
        for (let i = 0; i < this.state.selectedRows.length; i++) {
          res.push(productList.data_list[this.state.selectedRows[i]].id);
        }
        dispatch({
          type: 'MainProduct/deleteMainProductList',
          payload: {
            id: res.join(','),
          },
        });
      }
    };

    let handleTableSelectChange = selectedRows => {
      console.log(selectedRows);
      this.setState({ selectedRows });
    };

    let clearModalValues = () => {
      this.setState({
        modalId: undefined,
        modalProductName: '',
        modalProductType: 0,
        modalVisibility: false,
      });
    };

    let handleModalOk = e => {
      const { dispatch } = this.props;
      if (this.state.modalOperation === 'new') {
        dispatch({
          type: 'MainProduct/addMainProductList',
          payload: {
            product_name: this.state.modalProductName,
            product_type_id: this.state.modalProductType,
          },
        });
      } else {
        dispatch({
          type: 'MainProduct/updateMainProductList',
          payload: {
            id: this.state.modalId,
            product_name: this.state.modalProductName,
            product_type_id: this.state.modalProductType,
          },
        });
      }
      clearModalValues();
    };

    let handleModalCancel = e => {
      clearModalValues();
    };

    let handleModalProductNameChange = modalProductName => {
      this.setState({ modalProductName: modalProductName.target.value });
    };

    let handleModalProductTypeChange = modalProductType => {
      this.setState({ modalProductType });
    };

    return (
      <div style={{ margin: '24px 24px 0' }}>
        <div className={styles.outerWidthLim}>
          <div className={styles.outerHeightLim}>
            <div className={styles.contentCard}>
              <div className={styles.cardHeader}>
                <p className={styles.cardTitle}>主营产品</p>
                <div className={styles.operationBox}>
                  <a
                    onClick={() => {
                      this.setState({ modalVisibility: true, modalOperation: 'new' });
                    }}
                  >
                    添加
                  </a>
                  <span className={styles.smallGap}>|</span>
                  <a onClick={handleDeleteClick}>删除</a>
                </div>
                <Modal
                  title="添加主营产品"
                  okText="保存"
                  visible={this.state.modalVisibility}
                  onOk={handleModalOk}
                  onCancel={handleModalCancel}
                >
                  <div>
                    <span style={{ color: 'red' }}>*</span>
                    <span className={styles.SelectTitle}>业务分类：</span>
                    <Input
                      style={{ width: '75%' }}
                      value={this.state.modalProductName}
                      onChange={handleModalProductNameChange}
                    />
                  </div>
                  <div style={{ marginTop: '20px' }}>
                    <span style={{ color: 'red' }}>*</span>
                    <span className={styles.SelectTitle}>业务分类：</span>
                    <Select
                      style={{ width: '75%' }}
                      value={this.state.modalProductType}
                      onChange={handleModalProductTypeChange}
                    >
                      <Option value={0}>主营业务</Option>
                      <Option value={1}>其他业务</Option>
                    </Select>
                  </div>
                </Modal>
              </div>
              <div className={styles.cardContent}>
                <Table
                  className={styles.bigTable}
                  columns={cols}
                  rowSelection={{
                    selectedRowKeys: this.state.selectedRows,
                    onChange: handleTableSelectChange,
                  }}
                  dataSource={productList.data_list}
                  pagination={pager}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default MainProductsList;
